﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Data;
using System.Text;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;
using Microsoft.Windows.Controls;
using BaocaoNPC.common;
using Component;
using CMISLibrary;
//using busBaoCao;
using CMISLibrary.Libraries;
using System.IO;
using Microsoft.VisualBasic;
using BaocaoNPC.Usercontrols.reports;
using Ionic.Zip;
using bus_TienichNPC;


namespace NPC_TIENICH.Usercontrols
{
    /// <summary>
    /// Interaction logic for Xuatnhan_BCKDNPC.xaml
    /// </summary>
    public partial class Import_ChamnoOFFLINE : UserControl
    {
        #region Variables
        //bus_TienichNPC.cls_TienichNPC_bus bus = new bus_TienichNPC.cls_TienichNPC_bus();
        public string strMaPhanHe_BCao = "BC";
        public string strMaPhanHe_LViec = "BC";
        public String strMadviqly = NPCUS_DanhMuc.Pglobal.strMa_dviqly != "" && NPCUS_DanhMuc.Pglobal.strMa_dviqly != null ? NPCUS_DanhMuc.Pglobal.strMa_dviqly : "PA";
        public string strUsername = NPCUS_DanhMuc.Pglobal.strTen_dangnhap != "" && NPCUS_DanhMuc.Pglobal.strTen_dangnhap != null ? NPCUS_DanhMuc.Pglobal.strTen_dangnhap : "NPC_ATM";
        public String strTen_dviqly = NPCUS_DanhMuc.Pglobal.strTen_dviqly != "" && NPCUS_DanhMuc.Pglobal.strTen_dviqly != null ? NPCUS_DanhMuc.Pglobal.strTen_dviqly : "cty..";
        public String strTen_dviqly_CT = NPCUS_DanhMuc.Pglobal.strTen_dviqly_CT != "" && NPCUS_DanhMuc.Pglobal.strTen_dviqly_CT != null ? NPCUS_DanhMuc.Pglobal.strTen_dviqly_CT : "cap tren";
        public Int16 i16ThangHT = 0;
        public Int16 i16NamHT = 0;
        public int intIDLSuTHop = 0;
        public long pcount = 0;//so cong to duoc chon
        public long ptcount = 0;// tong so cong to load ra luoi
        public Decimal ptien = 0;
        string pasword = "NPCICT2012";
        public int daysInMonth_HT = 1;
        DataSet dsDvi = new DataSet();
        DataSet dsDSchamno = new DataSet();
        DataSet ds_DM_TNGAN = new DataSet();
        DataSet ds_CAPNHAT = new BCNPCEntities.EXCEL.ds_CAPNHAT();
        public string strThuMucGoc = "C:\\NPCUSConfig";
        public string pfile = "";
        public string strDonVi_chon;
        DataSet ds_nhanfile = new DataSet();
        int P_ERROS;
        string maloi="";
        #endregion
        public Import_ChamnoOFFLINE()
        {
            try
            {
                InitializeComponent();
                GET_THANGNAM_HT();
                GetD_DVI_QLY();
                daysInMonth_HT = System.DateTime.DaysInMonth(i16NamHT, i16ThangHT);
                dtpThangHT.Text = "0" + i16ThangHT.ToString() + "/" + i16NamHT.ToString();
                dtpThangHTtim.Text = "0" + i16ThangHT.ToString() + "/" + i16NamHT.ToString();
                dtptungay.Text  = "01/"+ i16ThangHT.ToString() + "/" + i16NamHT.ToString();
                dtpdenngay.Text = daysInMonth_HT.ToString()+"/" + i16ThangHT.ToString() + "/" + i16NamHT.ToString();
                ds_DM_TNGAN = GlobalServices.Service_NPCUS.get_DM_TNGAN(strMadviqly);
                txtthungan.AddItem(new CMIS2_TextBox.AutoCompleteEntry(ds_DM_TNGAN));
                btnNhanSL.IsEnabled = false;

            }
            catch
            { }
        }
        private void GET_THANGNAM_HT()
        {
            try
            {
                DataSet dsthanglviec = new DataSet();
                
                //dsthanglviec = bus.get_thang_lviec();
                dsthanglviec = GlobalServices.Service_NPCUS.get_thang_lviec();
                if (dsthanglviec != null && dsthanglviec.Tables.Count > 0)
                {
                    foreach (DataRow dr in dsthanglviec.Tables[0].Rows)
                        if (dr["PHAN_HE"].ToString() == "CN" && dr["MA_DVIQLY"].ToString() == strMadviqly)
                        {
                            i16ThangHT = Convert.ToInt16(dr["THANG"]);
                            i16NamHT = Convert.ToInt16(dr["NAM"]);
                        }
                }
            }
            catch
            {
                i16ThangHT = Convert.ToInt16(DateTime.Now.Month);
                i16NamHT = Convert.ToInt16(DateTime.Now.Year);
            }
        }
        private void GetD_DVI_QLY()
        {
            try
            {
                DataSet dsD_DVI_QLY = new DataSet();

               

                //dsD_DVI_QLY = cls.select_D_DVI_QLY_ALL(strMa_dviqly);

                dsD_DVI_QLY = GlobalServices.Service_NPCUS.select_D_DVI_QLY_ALL(strMadviqly);

                if (dsD_DVI_QLY == null)
                {
                    System.Windows.MessageBox.Show("Không lấy được danh mục đơn vị quản lý.");
                }
                else
                {
                    DataView dv = dsD_DVI_QLY.Tables["D_DVI_QLY"].DefaultView;
                    cboDonVi.ItemsSource = dv;
                    cboDonVi.DisplayMemberPath = "TEN_DVIQLY";
                    cboDonVi.SelectedValuePath = "MA_DVIQLY";
                    cboDonVi.SelectedIndex = 0;
                    cboDonVi1.ItemsSource = dv;
                    cboDonVi1.DisplayMemberPath = "TEN_DVIQLY";
                    cboDonVi1.SelectedValuePath = "MA_DVIQLY";
                    cboDonVi1.SelectedIndex = 0;
                }
            }
            catch (Exception ex)
            {
                System.Windows.MessageBox.Show(ex.Message.ToString());
            }
        }

        public void showErrorMess(string s)
        {
            Component.Validate.ValidationManager.showMessOnView(this, 5000, s, Component.Validate.ValidationManager.MESSEGER_TYPE.ERROR_MESSAGE);
        }
        public void showSucrMess(string s)
        {
            Component.Validate.ValidationManager.showMessOnView(this, 5000, s, Component.Validate.ValidationManager.MESSEGER_TYPE.SUCCESS_MESSAGE);
        }

 
        private void btnNhanSL_Click(object sender, RoutedEventArgs e)
        {
            try
            {
                string ERRO = "";
                if (pcount == 0)
                { showErrorMess("Không có hóa đơn nào được chọn chấm lần này"); return; }
                if (dsDSchamno == null || dsDSchamno.Tables.Count == 0)
                { showErrorMess("Không có dữ liệu chấm nợ"); return; }

                if (MessageBox.Show("Bạn có muốn cập nhật chấm nợ cho " + pcount + " hóa đơn không?", "Thông báo", MessageBoxButton.OKCancel, MessageBoxImage.Question) == MessageBoxResult.OK)
                {
                    // nhận số liệu vào off line
                    DataTable dt = dsDSchamno.Tables[0] as DataTable;
                    for (int i = 0; i < dsDSchamno.Tables[0].Rows.Count; i++)
                    {
                        if (dsDSchamno.Tables[0].Rows[i]["CHON"].ToString() == "True")
                        {
                            ds_CAPNHAT.Tables["NPC_CHAMNO_OFFLINE"].Rows.Clear();
                            DataRow dr = ds_CAPNHAT.Tables["NPC_CHAMNO_OFFLINE"].NewRow();
                            //dr["ID_CAYLUOIDIEN"] = OMS_DANHMUC.Pglobal.strMa_dviqly;
                            dr["MA_DVIQLY"] = dt.Rows[i]["MA_DVIQLY"].ToString();
                            dr["MA_KHANG"] = dt.Rows[i]["MA_KHANG"].ToString();
                            dr["ID_HDON"] = Convert.ToInt64(dt.Rows[i]["ID_HDON"]);
                            dr["TIEN_NOP"] = Convert.ToDecimal(dt.Rows[i]["SO_TIEN"].ToString());
                            dr["THUE_NOP"] = Convert.ToDecimal(dt.Rows[i]["TIEN_GTGT"].ToString());
                            dr["SO_BBGIAO"] = Convert.ToInt64(dt.Rows[i]["SO_BBGIAO"]);
                            dr["MA_TNGAN"] = dt.Rows[i]["MA_TNGAN"].ToString();
                            dr["MA_TNGAN_THUHO"] = dt.Rows[i]["MA_TNGAN"].ToString();
                            dr["NGAY_CHAMNO"] = Convert.ToDateTime(dt.Rows[i]["NGAY_NOP"]);
                            dr["NAM_HT"] = dt.Rows[i]["NAM"];
                            dr["THANG_HT"] = dt.Rows[i]["THANG"];
                            dr["TRANGTHAI"] = 0;
                            dr["GROUP_NHOM"] = 0;
                            dr["NGUOI_TAO"] = strUsername;
                            dr["TINHTRANGIN"] = dt.Rows[i]["TINHTRANGIN"];
                            dr["NGAY_TAO"] = DateTime.Now;
                            ds_CAPNHAT.Tables["NPC_CHAMNO_OFFLINE"].Rows.Add(dr);
                            ds_CAPNHAT.AcceptChanges();
                            
                            //if (!cls.insert_NPC_CHAMNO_OFFLINE(ds_CAPNHAT, ref maloi))
                            if (!GlobalServices.Service_NPCUS.insert_NPC_CHAMNO_OFFLINE(ds_CAPNHAT, ref maloi))
                            {
                                TootsNPC.ShowMessage.SetStatus("ERORR",this,btnNhanSL,"lblstatus",maloi);
                            
                                return;
                            }
                            //Ghilog
                            ds_CAPNHAT.Tables["NPC_CHAMNO_OFFLINE_LOG"].Rows.Clear();
                            DataRow drlog = ds_CAPNHAT.Tables["NPC_CHAMNO_OFFLINE_LOG"].NewRow();
                            drlog["MA_DVIQLY"] = dt.Rows[i]["MA_DVIQLY"].ToString();
                            drlog["MA_KHANG"] = dt.Rows[i]["MA_KHANG"].ToString();
                            drlog["ID_HDON"] = Convert.ToInt64(dt.Rows[i]["ID_HDON"]);
                            drlog["SO_BBGIAO"] = Convert.ToInt64(dt.Rows[i]["SO_BBGIAO"]);
                            drlog["NAM_HT"] = dt.Rows[i]["NAM"];
                            drlog["THANG_HT"] = dt.Rows[i]["THANG"];
                            drlog["MA_TNGAN"] = dt.Rows[i]["MA_TNGAN"].ToString();
                            drlog["NGAY_CHAMNO"] = Convert.ToDateTime(dt.Rows[i]["NGAY_NOP"]);
                            drlog["TRANGTHAI"] = 3;
                            drlog["NGUOI_TAO"] = strUsername;
                            drlog["NGAY_TAO"] = DateTime.Now;
                            drlog["GIO"] = DateTime.Now.Hour;
                            ds_CAPNHAT.Tables["NPC_CHAMNO_OFFLINE_LOG"].Rows.Add(drlog);
                            ds_CAPNHAT.AcceptChanges();
                            if (!GlobalServices.Service_NPCUS.insert_NPC_CHAMNO_OFFLINE_LOG(ds_CAPNHAT, ref maloi))
                            {
                                TootsNPC.ShowMessage.SetStatus("ERORR", this, btnNhanSL, "lblstatus", maloi);
                                //chamno = false;
                            }
                        }
                    }
                }
                TootsNPC.ShowMessage.SetStatus("SUCCESS", this, btnNhanSL, "lblstatus", "Nhận số liệu thành công!");
            }
            catch (Exception ex)
            { showErrorMess(ex.ToString()); }
        }
        
        private void btnChonDuongDan_Click(object sender, RoutedEventArgs e)
        {
            System.Windows.Forms.OpenFileDialog fld = new System.Windows.Forms.OpenFileDialog();
            fld.Title = "Select file to Update";
            fld.Filter = "Winrar Files(*.rar)|*.rar";
            try
            {               
            if (fld.ShowDialog() == System.Windows.Forms.DialogResult.OK)
            {
                txtDuongDan.Text = fld.FileName.ToString();
            }
            if (txtDuongDan.Text.Length > 0)
            {
                string[] filenames = txtDuongDan.Text.Split('\\');
                foreach (string sfilename in filenames)
                {
                    if (sfilename.Contains(".rar"))
                        pfile = sfilename.Substring(0,sfilename.Length - 4);
                }
            }
            }
            catch
            {
                //fld.SelectedPath = "My Computer";
            }
        }

        private void chkDaochon_Click(object sender, RoutedEventArgs e)
        {

        }

        private void txtTimKiemMA_KHANG_KeyDown(object sender, KeyEventArgs e)
        {

        }

        private void txtTimKiemID_HDON_KeyDown(object sender, KeyEventArgs e)
        {

        }

        
        private void txtTimKiemMA_KHANG_TextChanged(object sender, TextChangedEventArgs e)
        {
            try
            {
                string s = txtTimKiemMA_KHANG.Text;
                if (s.Trim() == "")
                {
                    dgrdschamno.SelectedIndex = 0;
                    return;
                }
                DataTable dt = dsDSchamno.Tables["DSNO"] as DataTable;
                DataRow[] dr = dt.Select("MA_KHANG LIKE '%" + s.ToUpper() + "%'", "MA_KHANG");
                if (dr.Count() == 0)
                {
                    dgrdschamno.SelectedIndex = 0;
                    return;
                }
                else
                {
                    for (int i = 0; i < dgrdschamno.Items.Count; i++)
                    {
                        DataGridRow row = (DataGridRow)dgrdschamno.ItemContainerGenerator.ContainerFromIndex(i);
                        TextBlock cellContent = dgrdschamno.Columns[3].GetCellContent(row) as TextBlock;
                        if (cellContent != null && cellContent.Text.ToUpper().Contains(txtTimKiemMA_KHANG.Text.ToUpper()))
                        {
                            object item = dgrdschamno.Items[i];
                            dgrdschamno.SelectedItem = item;
                            dgrdschamno.ScrollIntoView(item);
                            row.MoveFocus(new TraversalRequest(FocusNavigationDirection.Next));
                            txtTimKiemMA_KHANG.Focus();
                            break;
                        }
                    }

                }
            }
            catch (Exception ex)
            { showErrorMess(ex.ToString()); }
        }

        private void txtTimKiemID_HDON_TextChanged(object sender, TextChangedEventArgs e)
        {

            try
            {
                string s = txtTimKiemID_HDON.Text;
                if (s.Trim() == "")
                {
                    dgrdschamno.SelectedIndex = 0;
                    return;
                }
                DataTable dt = dsDSchamno.Tables["DSNO"] as DataTable;
                DataRow[] dr = dt.Select("ID_HDON = '" + s.ToUpper() + "'", "ID_HDON");
                if (dr.Count() == 0)
                {
                    dgrdschamno.SelectedIndex = 0;
                    return;
                }
                else
                {
                    for (int i = 0; i < dgrdschamno.Items.Count; i++)
                    {
                        DataGridRow row = (DataGridRow)dgrdschamno.ItemContainerGenerator.ContainerFromIndex(i);
                        TextBlock cellContent = dgrdschamno.Columns[9].GetCellContent(row) as TextBlock;
                        if (cellContent != null && cellContent.Text.ToUpper().Contains(txtTimKiemID_HDON.Text.ToUpper()))
                        {
                            object item = dgrdschamno.Items[i];
                            dgrdschamno.SelectedItem = item;
                            dgrdschamno.ScrollIntoView(item);
                            row.MoveFocus(new TraversalRequest(FocusNavigationDirection.Next));
                            txtTimKiemID_HDON.Focus();
                            break;
                        }
                    }

                }
            }
            catch (Exception ex)
            { showErrorMess(ex.ToString()); }
        }

        private void btnChapnhan_Click(object sender, RoutedEventArgs e)
        {
            try
            {
                string P_Path;
                //Me.Cursor = System.Windows.Forms.Cursors.WaitCursor
                ds_nhanfile = new DataSet();

                strDonVi_chon = cboDonVi.SelectedValue.ToString();
                string sfilename = txtDuongDan.Text;
                P_Path = sfilename.Substring(0, sfilename.Length - 4);
                #region Giai nen
                // xóa thư mục truoc khi giai nen
                if (System.IO.Directory.Exists(P_Path))
                {
                    try
                    {
                        System.IO.Directory.Delete(P_Path, true);
                    }

                    catch (System.IO.IOException ex)
                    {
                        showErrorMess(ex.ToString());
                    }
                }
                //giai nen
                using (ZipFile zip = ZipFile.Read(sfilename))
                {
                    zip.Password = pasword;
                    zip.ExtractAll(P_Path);
                }
                #endregion

                string fileXML = P_Path + @"\" + pfile + ".XML";
                if (System.IO.File.Exists(fileXML))
                {

                    ds_nhanfile.ReadXml(fileXML);
                }
                else
                { showErrorMess("Lỗi không tìm thấy file"); return; }
                //xoa file da giai nen
                TootsNPC.compression.deletefile(P_Path);
                if (ds_nhanfile == null || ds_nhanfile.Tables.Count == 0)
                { showErrorMess("File không có dữ liệu"); return; }
                if (ds_nhanfile != null && ds_nhanfile.Tables[0].Rows.Count > 0)
                {
                    
                    dsDSchamno= new DataSet();
                    
                    //dsDSchamno = bus.get_dsno(ds_nhanfile, strDonVi_chon);
                    dsDSchamno = GlobalServices.Service_NPCUS.get_dsno(ds_nhanfile, strDonVi_chon);
                }
                if (dsDSchamno == null || dsDSchamno.Tables["DSNO"].Rows.Count == 0)
                { showErrorMess("Không lấy được dữ liệu công nợ"); return; }
                pcount = dsDSchamno.Tables["DSNO"].Rows.Count;
                ptcount = dsDSchamno.Tables["DSNO"].Rows.Count;
                foreach (DataRow dr in dsDSchamno.Tables["DSNO"].Rows)
                {
                    ptien = ptien + Convert.ToDecimal(dr["SO_TIEN"]) + Convert.ToDecimal(dr["TIEN_GTGT"]);
                    if(Convert.ToInt64(dr["SO_TIEN"])!= Convert.ToInt64(dr["TIEN_NO"]))
                    {
                        dr["CHON"]= "False";
                        ptien = ptien - (Convert.ToDecimal(dr["SO_TIEN"]) + Convert.ToDecimal(dr["TIEN_GTGT"]));
                        pcount = pcount - 1;
                    }
                }

                dgrdschamno.ItemsSource = dsDSchamno.Tables["DSNO"].DefaultView;
                dsDSchamno.Tables["DSNO"].DefaultView.AllowNew = false;
                lblTongSo.Content = "Tổng số:" + pcount.ToString() + "/" + ptcount;
                lblTongtien.Content = "Tổng tiền:" + ptien.ToString("# ### ### ###");
                if (pcount > 0)
                {
                    btnNhanSL.IsEnabled = true;
                }
                else btnNhanSL.IsEnabled = false;

                //Me.Cursor = System.Windows.Forms.Cursors.Default
            }
            catch (Exception ex)
            {
                showErrorMess(ex.ToString());

            }
        }

        private void btnIN_Click(object sender, RoutedEventArgs e)
        {
            try
            {
                string strMatngan = "";
                DataSet ds_chamnooffline = new DataSet();
                DateTime? ptungay, pdenngay;
                int id1 = txtthungan.Text.IndexOf("-");
                ptungay = dtptungay.SelectedDate;
                pdenngay = dtpdenngay.SelectedDate;
                if (id1 == -1)
                { strMatngan = ""; }
                else
                {
                    strMatngan = txtthungan.Text.Substring(0, id1);
                }
                Int16 pthangIn =  Convert.ToInt16(dtpThangHTtim.Text.Substring(0, 2)); ;

                Int16 pnamIn = Convert.ToInt16(dtpThangHTtim.Text.Substring(3, 4));
                int ilsu = 0; //0: hien tai, 1: lich su
                if (pthangIn == i16ThangHT && pnamIn == i16NamHT)
                    ilsu = 0;
                else ilsu = 1;

                ds_chamnooffline = GlobalServices.Service_NPCUS.get_dschamno(strMadviqly, strMatngan, pthangIn, pnamIn, ilsu, ptungay, pdenngay);
                if (ds_chamnooffline == null || ds_chamnooffline.Tables.Count == 0)
                { showErrorMess("Không có dữ liệu theo điều kiện chọn"); return; }
                if (ds_chamnooffline.Tables["DSCHAMNO"].Rows.Count > 0)
                {
                    rptDsChamno_Offline rpt = new rptDsChamno_Offline();
                    rpt.SetDataSource(ds_chamnooffline.Tables["DSCHAMNO"]);
                    rpt.SetParameterValue("ptungay", ptungay);
                    rpt.SetParameterValue("pdenngay", pdenngay);
                    rpt.SetParameterValue("pTendienluc", strTen_dviqly);
                    rpt.SetParameterValue("pTencongty", strTen_dviqly_CT);
                    //ds_chamnooffline.WriteXmlSchema("D:\\Projects\\DSCHAMNO.xsd");
                    UtilReportOMS.RptManager.showReportToWin(this, rpt, strMadviqly, new string[] { "Formula1", "Formula2", "Formula3" }, new string[] { "Formula1", "Formula2", "Formula3" }, "CMIS2 - Report: Báo cáo NPC");
                }
                else
                { showErrorMess("Không có dữ liệu theo điều kiện chọn"); return; }
            }
            catch
            {}
        }

       
    }
}
